<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator=">">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <!-- 搜索添加区域 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <!-- 绑定query属性 将其传到后端处理 再返回最新数据 此时点击搜索按钮重新发起axios请求 来请求匹配数据 -->
          <el-input
            placeholder="请输入商品名称"
            v-model="queryInfo.query"
            clearable
            @clear="getGoodsList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getGoodsList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="goAddpage"> 添加商品 </el-button>
        </el-col>
      </el-row>
      <!-- 表格区域 -->
      <el-table :data="goodsList" border stripe>
        <el-table-column type="index" :resizable="false"></el-table-column>
        <el-table-column
          label="商品名称"
          prop="goods_name"
          :resizable="false"
        ></el-table-column>
        <el-table-column
          label="商品价格(元)"
          prop="goods_price"
          width="120px"
          :resizable="false"
        ></el-table-column>
        <el-table-column
          label="商品重量"
          prop="goods_weight"
          width="90px"
          :resizable="false"
        ></el-table-column>
        <el-table-column
          label="创建时间"
          prop="add_time"
          width="180px"
          :resizable="false"
        >
          <template #default="scope">
            <!-- 过滤器格式化时间 -->
            {{ scope.row.add_time | dateFormat }}
          </template></el-table-column
        >
        <el-table-column label="操作" width="130px" :resizable="false">
          <template #default="scope">
            <!-- 修改按钮 -->
            <el-tooltip
              class="item"
              effect="dark"
              content="修改按钮"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="mini"
                @click="showEditDialog(scope.row.goods_id)"
              ></el-button>
            </el-tooltip>
            <!-- 删除按钮 -->
            <el-tooltip
              class="item"
              effect="dark"
              content="删除按钮"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="removeUserById(scope.row.goods_id)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 编辑商品信息的对话框 -->
    <el-dialog
      title="编辑分类"
      :visible.sync="editGoodsDialogVisible"
      width="80%"
      @close="editGoodsClosed"
    >
      <el-alert
        title="编辑商品信息"
        type="info"
        center
        show-icon
        :closable="false"
      >
      </el-alert>
      <!-- 分割线 -->
      <el-divider></el-divider>
      <el-form
        ref="editGoodsFormRef"
        :model="editGoodsForm"
        label-width="80px"
        :rules="editGoodsRules"
      >
        <!-- 基本信息 -->
        <el-form-item label="商品名称" prop="goods_name">
          <el-input v-model="editGoodsForm.goods_name"></el-input>
        </el-form-item>
        <el-form-item label="商品价格" prop="goods_price">
          <el-input
            v-model="editGoodsForm.goods_price"
            type="number"
          ></el-input>
        </el-form-item>
        <el-form-item label="商品重量" prop="goods_weight">
          <el-input
            v-model="editGoodsForm.goods_weight"
            type="number"
          ></el-input>
        </el-form-item>
        <el-form-item label="商品数量" prop="goods_number">
          <el-input
            v-model="editGoodsForm.goods_number"
            type="number"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editGoodsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editGoods(editGoodsForm.goods_id)"
          >修 改</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 列表数据
      queryInfo: {
        query: "",
        pagenum: 1,
        pagesize: 10,
      },
      // 商品总数
      total: 0,
      // 商品数据列表
      goodsList: [],
      // 控制编辑商品对话框的打开与关闭
      editGoodsDialogVisible: false,
      // 编辑商品的数据表单
      editGoodsForm: {},
      // 图片上传的api接口地址
      uploadUrl: "http://127.0.0.1:8888/api/private/v1/upload",
      // 图片上传的header请求头
      herderObj: {
        Authorization: window.sessionStorage.getItem("token"),
      },
      // 图片预览url地址
      previewPath: "",
      // 控制打开预览图片的对话框
      previewVisible: false,

      // 编辑商品的规则
      editGoodsRules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
        goods_price: [
          { required: true, message: "请输入商品价格", trigger: "blur" },
        ],
        goods_weight: [
          { required: true, message: "请输入商品重量", trigger: "blur" },
        ],
        goods_number: [
          { required: true, message: "请输入商品数量", trigger: "blur" },
        ],
      },
      activeIndex: "0",
      // 侧边栏方向
      tabPosition: "left",
    };
  },
  created() {
    this.getGoodsList();
  },
  methods: {
    // 得到商品列表
    async getGoodsList() {
      const { data: res } = await this.$http.get("goods", {
        params: this.queryInfo,
      });
      // console.log(res);
      if (res.meta.status !== 200) return this.$message.error("获取失败");
      this.$message.success("获取成功");
      this.goodsList = res.data.goods;
      this.total = res.data.total;
    },
    // 显示编辑对话框
    async showEditDialog(id) {
      this.editGoodsDialogVisible = true;
      const { data: res } = await this.$http.get(`goods/${id}`);
      if (res.meta.status !== 200) {
        return this.$message.error("请求商品信息失败");
      }
      this.editGoodsForm = res.data;
      // console.log(this.editGoodsForm);
    },
    // 显示删除对客户
    async removeUserById(id) {
      const confirmResult = await this.$confirm(
        "此操作将永久删除该商品, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (confirmResult !== "confirm")
        return this.$message.info("已取消删除操作");
      const { data: res } = await this.$http.delete(`goods/${id}`);
      if (res.meta.status !== 200) return this.$message.error("删除失败");
      this.$message.success("删除成功");
      this.getGoodsList();
    },
    // 每页条数发生变化时调用该函数
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize;
      this.getGoodsList();
    },
    // 页数发生变化时调用该函数
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage;
      this.getGoodsList();
    },
    // 点击按钮打开添加商品对话框
    goAddpage() {
      this.$router.push("goods/add");
    },
    // 点击按钮修改商品信息
    editGoods(id) {
      this.$refs.editGoodsFormRef.validate(async (valid) => {
        if (!valid) {
          return this.$message.error("请填写必要数据项");
        }
        const { data: res } = await this.$http.put(
          `goods/${id}`,
          this.editGoodsForm
        );
        if (res.meta.status !== 200) {
          return this.$message.error("修改失败");
        }
        this.getGoodsList();
        this.editGoodsDialogVisible = false;
        this.$message.success("修改成功");
      });
    },
    // 对话框关闭触发该函数
    editGoodsClosed() {
      this.$refs.editGoodsFormRef.resetFields();
    },
    //tab被选中时触发
    async tabClicked() {
      // console.log(this.activeIndex);
      // 选择第一个tab项
      if (this.activeIndex === "1") {
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          { params: { sel: "many" } }
        );
        if (res.meta.status !== 200) {
          return this.$message.error("获取动态参数失败");
        }
        res.data.forEach((item) => {
          item.attr_vals =
            item.attr_vals.length === 0 ? [] : item.attr_vals.split(",");
        });
        this.manyTableData = res.data;
        // console.log(this.manyTableData);
      }
      // 选择第二个tab项
      else if (this.activeIndex === "2") {
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          { params: { sel: "only" } }
        );
        if (res.meta.status !== 200) {
          return this.$message.error("获取静态属性失败");
        }
        // console.log(res.data);
        this.onlyTableData = res.data;
      }
    },
  },
};
</script>

<style lang="less" scoped>
.el-steps {
  margin-top: 15px;
}
</style>
